<!--短信发送-->
<template>
	<a-card :bordered="false">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState">
			<a-row :gutter="24">
				<a-col :span="5">
					<a-form-item label="手机号：" name="phone">
						<a-input v-model:value="searchFormState.phone" placeholder="请输入手机号" allow-clear  />
					</a-form-item>
				</a-col>
				<a-col :span="5">
					<a-form-item label="创建人" name="createUser">
						<UserSelect v-model:value="searchFormState.createUser"  />
					</a-form-item>
				</a-col>
				<a-col :span="5">
					<a-form-item label="所属公司" name="deptId">
						<a-tree-select
							v-model:value="searchFormState.deptId"
							class="xn-wd"
							:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
							placeholder="请选择所属公司"
							allow-clear
							tree-default-expand-all
							:tree-data="treeData"
							:tree-default-expanded-keys="treeDefaultExpandedKeys"
							:field-names="{
								children: 'children',
								label: 'name',
								value: 'id'
							}"
						></a-tree-select>
					</a-form-item>
				</a-col>
				<a-col :span="5">
					<a-form-item label="日期范围">
						<a-range-picker v-model:value="dateRange" valueFormat="YYYY-MM-DD" :allowClear="false" />
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-button type="primary" @click="tableRef.refresh(true)">查询</a-button>
					<a-button style="margin: 0 8px" @click="reset">重置</a-button>
				</a-col>
			</a-row>
		</a-form>
	</a-card>
	<a-card :bordered="false" class="mt-2">
		<s-table
			ref="tableRef"
			:columns="columns"
			:data="loadData"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:scroll="{ x: 'max-content' }"
		>
			<template #operator>
				<a-space>
					<a-button type="primary" @click="uploadRef.openUpload()">
						<template #icon>
							<import-outlined  />
						</template>
						导入
					</a-button>
					<a-button v-if="hasPerm('sendSseMsg')" type="primary" @click="visibleSseMsgModal = true">
						<template #icon>
							<comment-outlined />
						</template>
						站内消息
					</a-button>
				</a-space>
			</template>
			<template #bodyCell="{ column, record, text }">
				<!--				<template-->
				<!--					v-if="column.dataIndex === 'completedQuantity'">-->
				<!--					<a-progress-->
				<!--						:percent="text"-->
				<!--						:stroke-color="getProgressColor(text)"-->
				<!--						:status="text >= 100 ? 'success' : 'normal'"-->
				<!--						stroke-linecap="round"-->
				<!--						:size="[300, 20]"-->
				<!--						:format="formatText"-->
				<!--						text-position="inside"-->
				<!--					/>-->
				<!--				</template>-->
				<template v-if="column.dataIndex === 'sendProgress'">
					{{ Math.max(((record.completedQuantity / record.totalQuantity) * 100).toFixed(2), 0) }}%
				</template>
				<template v-if="column.dataIndex === 'successQuantity'">
					{{ Math.max(((record.successQuantity / record.totalQuantity) * 100).toFixed(2), 0) }}%（持续更新中）
				</template>
				<template v-if="column.dataIndex === 'action'">
					<a-button
						type="link"
						size="small"
						v-if="record.batchStatus === '1'"
						:loading="record.testLoading"
						@click="sendSms(record)"
							>测试
					</a-button>
					<a-button
						type="link"
						size="small"
						v-if="record.batchStatus === '2'"
						@click="startSend(record)"
						:loading="record.startLoading"
					>
						开始
					</a-button>
					<a-button type="link" size="small" @click="detailRef.openDetail(record)">详情</a-button>
					<a-button type="link" size="small" @click="statisDrawer(record)">统计</a-button>
				</template>
			</template>
		</s-table>
	</a-card>
	<Upload ref="uploadRef" @successful="tableRef.refresh(true)"  />
	<Detail ref="detailRef"  />
	<!--	<a-modal v-model:open="phoneModalVisible" title="测试短信" @ok="sendSms">-->
	<!--		<a-form-item label="手机号">-->
	<!--			<a-input-->
	<!--				v-model:value="testPhone"-->
	<!--				placeholder="请输入手机号"-->
	<!--				allow-clear-->
	<!--			/>-->
	<!--		</a-form-item>-->
	<!--	</a-modal>-->
	<!-- 统计弹框 -->
	<a-drawer
		v-model:open="statisOpen"
		title="统计"
		placement="right"
		width="85%"
		@close="closeDrawer"
		class="statisDrawer"
	>
		<a-card title="路由发送情况" :bordered="false" class="statis-card">
			<a-spin :spinning="statisLoading">
				<div id="statisBar"></div>
			</a-spin>
		</a-card>
		<a-card title="发送结果分布" :bordered="false" class="m-t-24 statis-card">
			<a-spin :spinning="statisPieLoading">
				<div id="statisPie"></div>
			</a-spin>
		</a-card>
	</a-drawer>
	<a-modal title="站内消息" v-model:open="visibleSseMsgModal" @ok="sendSseMsg">
		<a-textarea v-model:value="sseMsgContent" />
	</a-modal>
</template>
<script setup name="smsBatch">
		import Upload from '@/views/tjzy/sms/batch/upload.vue'
		import Detail from '@/views/tjzy/sms/batch/detail.vue'
		import smsBatchApi from '@/api/tjzy/sms/smsBatchApi'
		import UserSelect from '@/components/XnUserSelector/userSelect.vue'
		import bizUserApi from '@/api/biz/bizUserApi'
		import smsRecordApi from '@/api/tjzy/sms/smsReceiptApi'
		import {  Bar  } from '@antv/g2plot'
		import {  Pie  } from '@antv/g2plot'
		import {  yzErrorCode  } from '@/utils/smsErrorCode'
		import dayjs from 'dayjs'
	import sseApi from '@/api/tjzy/sse/sseApi'

		const searchFormRef = ref()
		const searchFormState = ref({
			current: 1,
			size: 10,
			phone: '',
			createUser: '',
			deptId: ''
		})
		const treeData = ref([])
		const treeDefaultExpandedKeys = ref([])
		const tableRef = ref()
		const uploadRef = ref()
		const detailRef = ref()
	const visibleSseMsgModal = ref(false)
	const sseMsgContent = ref()
		const toolConfig = {  refresh: true, height: true, columnSetting: false, striped: false  }
		const columns = [
			{
				title: '批次号',
				dataIndex: 'batchNumber'
			},
			{
				title: '所属项目',
				dataIndex: 'projectName'
			},
			{
				title: '批次名称',
				dataIndex: 'batchName'
			},
			{
				title: '模版名称',
				dataIndex: 'templateName'
			},
			{
				title: '路由顺序',
				dataIndex: 'supplierOrder'
			},
			{
				title: '总数',
				dataIndex: 'totalQuantity'
			},
			{
				title: '发送进度',
				dataIndex: 'sendProgress'
			},
			{
				title: '成功率',
				dataIndex: 'successQuantity'
			},
			{
				title: '创建人',
				dataIndex: 'createUserName'
			},
			{
				title: '创建时间',
				dataIndex: 'createTime',
				ellipsis: true
			},
			{
				title: '操作',
				dataIndex: 'action',
				align: 'center'
			}
		]
		let statisLoading = ref(false)
	let statisPieLoading = ref(false)
	let statisOpen = ref(false) //统计抽屉是否打开
		let statisBarPlot = null // 添加图表实例变量
		let piePlot = null //饼图实例
		let dateRange = ref([
			dayjs().subtract(6, 'day').format('YYYY-MM-DD'), // 今天减去7天
			dayjs().format('YYYY-MM-DD') // 今天的日期
		]) //日期范围
		//表单重置
		const reset = () => {
			searchFormRef.value.resetFields()
			dateRange.value = [
				dayjs().subtract(6, 'day').format('YYYY-MM-DD'), // 今天减去7天
				dayjs().format('YYYY-MM-DD') // 今天的日期
			]
			tableRef.value.refresh(true)
		}
		const loadData = (parameter) => {
			searchFormState.value.current = parameter.current
			searchFormState.value.size = parameter.size
			searchFormState.value.beginTime = `${dateRange.value[0]} 00:00:00`
			searchFormState.value.endTime = `${dateRange.value[1]} 23:59:59`
			return smsBatchApi.pageList(searchFormState.value).then((res) => {
				return res
			})
		}

	const sendSms = (record) => {
		record.testLoading = true
		// phoneModalVisible.value = false
		smsBatchApi
			.testSend(record.batchNumber)
			.then((res) => {
				tableRef.value.refresh(true)
				record.testLoading = false
			})
			.catch((err) => {
				record.testLoading = false
			})
	}

		const startSend = (record) => {
			record.startLoading = true
			smsBatchApi
				.startSend(record.batchNumber)
				.then((res) => {
					record.startLoading = false
					tableRef.value.refresh(true)
				})
				.catch((err) => {
					record.startLoading = false
				})
		}
		onMounted(() => {
			bizUserApi.userOrgTreeSelector().then((res) => {
				if (res !== null) {
					treeData.value = res
					// 默认展开2级
					treeData.value.forEach((item) => {
						// 因为0的顶级
						if (item.parentId === '0') {
							treeDefaultExpandedKeys.value.push(item.id)
							// 取到下级ID
							if (item.children) {
								item.children.forEach((items) => {
									treeDefaultExpandedKeys.value.push(items.id)
								})
							}
						}
					})
				}
			})
		})
		//打开统计抽屉
		const statisDrawer = (record) => {
			statisOpen.value = true
			statisLoading.value = true
		statisPieLoading.value = true
		//获取条形统计数据
			smsBatchApi.statisData(record.batchNumber).then((res) => {
				statisLoading.value = false
			// 处理数据结构
				const transformedData = res.statisticVoList.reduce((acc, item) => {
					acc.push(
						{
							supplierCode: item.supplierCode,
							type: '计费条数',
							value: item.billableNum
						},
						{
							supplierCode: item.supplierCode,
							type: '成功条数',
							value: item.successNum
						},
						{
							supplierCode: item.supplierCode,
							type: '失败条数',
							value: item.failedNum
						},
						{
							supplierCode: item.supplierCode,
							type: '发送中',
							value: item.unknowNum
						}
					)
					return acc
				}, [])

			//处理备注显示
			let annotationsArr = []
			// console.log('ress', res.statisticVoList)

			res.statisticVoList.forEach((item, i) => {
				annotationsArr.push({
					type: 'text',
					position: [item.supplierCode, 'end'],
					content: () => {
						if (i === 0) {
							return `发送成功率${item.successRate ? (item.successRate * 100).toFixed(2) : '0.00'}%`
						} else {
							return `提升成功率${
								item.successImprovementRate ? (item.successImprovementRate * 100).toFixed(2) : '0.00'
							}%`
						}
					},
					style: {
						fontSize: 12
					},
					offsetX: 15
				})
			})
			//绘图配置
			nextTick(() => {
				//条图======================================
				statisBarPlot = new Bar('statisBar', {
					data: transformedData,
					width: 300,
					isGroup: true,
					xField: 'value',
					yField: 'supplierCode',
					/** 自定义颜色 */
					// color: ['#5AD8A6', '#E8684A', '#5D7092'],
					seriesField: 'type',
					marginRatio: 0,
					// 增加右侧边距，为文本留出空间
					// maxBarWidth: 30,
					// dodgePadding: 0,
					padding: [30, 130, 20, 30],
					annotations: annotationsArr,
					legend: {
						position: 'top'
					},
					label: {
						// 可手动配置 label 数据标签位置
						position: 'middle', // 'left', 'middle', 'right'
						// 可配置附加的布局方法
						layout: [
							// 柱形图数据标签位置自动调整
							{ type: 'interval-adjust-position' },
							// 数据标签防遮挡
							{ type: 'interval-hide-overlap' }
							// 数据标签文颜色自动调整
							// { type: 'adjust-color' }
						]
					}
				})

					statisBarPlot.render()
				})
			})
			//获取饼图统计数据
			smsRecordApi.getcountByBatchNumber(record.batchNumber).then((res) => {
				statisPieLoading.value = false
			//绘图配置
				nextTick(() => {
					// 处理饼图数据
					const pieData = Object.entries(res).map(([code, value]) => {
						// 查找错误码对应的标签
						const errorItem = yzErrorCode.find((item) => item.code === code)
						return {
							type: errorItem ? errorItem.label : code,
							value: value
						}
					})
					// console.log('处理后的数据', pieData);
					piePlot = new Pie('statisPie', {
						appendPadding: 10,
						data: pieData,
						angleField: 'value',
						colorField: 'type',
						radius: 0.75,

					label: {
						type: 'spider',
						labelHeight: 28,
						content: ({ value, type }) => {
							const percentage = ((value / record.completedQuantity) * 100).toFixed(2)
							return `${type}：${percentage}%`
						}
					},
					// label: {
					// 	type: 'spider',
					// 	labelHeight: 28,
					// 	content: '{name}\n{percentage}'
					// },
					interactions: [{ type: 'element-selected' }, { type: 'element-active' }]
				})
				piePlot.render()
			})
		})
	}

		//关闭统计抽屉
		const closeDrawer = () => {
			statisBarPlot.destroy()
			piePlot.destroy()
			statisBarPlot = null
			piePlot = null
		}

	const sendSseMsg = () => {
		if (sseMsgContent.value) {
			sseApi.sendAll('CALL_LINE_CHANGES', sseMsgContent.value)
			visibleSseMsgModal.value = false
		}
	}
</script>

<style lang="less" scoped>
	.statis-card {
		height: 50%;

			:deep(.ant-card-body) {
				display: flex;
			justify-content: center;
			align-items: center;
			height: 80%;
			}

		#statisBar,
		#statisPie {
			height: 100%;
		}
	}
</style>
<style lang="less">
	.statisDrawer {
		.ant-drawer-body {
			background-color: #f5f5f5;
		}
	}
</style>
